<?php

namespace app\common\model;

use app\common\BaseModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\Model;

class ProductCategory extends BaseModel
{
    public static $fieldTypes = [
        'id' => 'number',
        'aid' => 'number',
        'status' => 'number',
        'category_name' => 'string',
        'created_at'  => 'date',
    ];

    public function manager()
    {
        return $this->belongsTo(AdminUser::class);
    }

    public function product()
    {
        return $this->hasMany(Product::class, 'cate_id');
    }

    /**
     * 保存数据
     * @param $data
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public static function saveData($data)
    {
        if(empty($data['id'])) {
            if(self::findCategoryName($data['category_name'])) {
                throw new Exception('商品名称不能重复');
            }

            if(!empty($data['img_url'])) {
                if(!file_exists(public_path() .'storage/'. $data['img_url'])) {
                    throw new Exception('商品分类图片不存在');
                }
            }

            self::insertGetId([
                'aid' => request()->user['user_id'],
                'img_url' => $data['img_url'],
                'category_name' => $data['category_name'],
            ]);
        }else{
            if(!$modelRecord = self::findById($data['id'])) {
                throw new Exception('商品分类不存在或已删除');
            }

            if(!empty($data['category_name'])) {
                if($modelRecord->category_name != $data['category_name']) {
                    if(self::findCategoryName($data['category_name'])) {
                        throw new Exception('商品分类名称不能重复');
                    }
                }

                $modelRecord->category_name = $data['category_name'];
            }

            if(!empty($data['img_url'])) {
                if(!file_exists(public_path() . 'storage/' . $data['img_url'])) {
                    throw new Exception('商品分类图片不存在');
                }

                $modelRecord->img_url = $data['img_url'];
            }

            if(isset($data['status'])) {
                $modelRecord->status = $data['status'];
            }

            $modelRecord->save();
        }
    }

    /**
     * 根据商品分类名称查询
     * @param $categoryName
     * @return BaseModel|array|mixed|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function findCategoryName($categoryName) {
        return self::findNoDeleted(['category_name' => $categoryName]);
    }
}